<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/6/16
 * Time: 16:58
 */

namespace common\models;


use yii\web\HttpException;

class AutoValidate {
    public $user = 1;

    public static function get($name){
        switch ($name) {
            case 'code':
                return Validate::$code;
                break;
            case 'tel':
                return Validate::$tel;
                break;
            case 'rec':
            case 'res':
                $rule = Validate::$tel;
                $rule['msg'] = '推荐人手机号码为11位有效数字!';
                return $rule;
                break;
            case 'branch':
                $rule = Validate::$bank_branch;
                $rule['msg'] = '请输入开户银行名称!';
                return $rule;
                break;
            case 'city':
                $rule = Validate::$bank_branch;
                $rule['msg'] = '请输入开户行所在市!';
                return $rule;
                break;
            case 'password':
                return Validate::$password;
                break;
            case 'id_no':
                return Validate::$identity;
                break;
            case 'card_no':
                return Validate::$bank_card;
                break;
            case 'money_order':
                return Validate::$money;
                break;
            case 'hongbao':
                $rule = Validate::$money;
                $rule['msg'] = '请输入正确格式的红包金额!';
                return $rule;
                break;
            case 'id':
            case 'couponID':
            case 'typeID':
                return Validate::$id;
                break;
            case 'hb_amount':
                $rule = Validate::$id;
                $rule['msg'] = '红包个数为大于0的正整数!';
                return $rule;
                break;
            case 'acct_name':
                if(\Yii::$app->request->isAjax)
                    return ['rule'=>"/^[\x{4e00}-\x{9fa5}_a-zA-Z]{2,10}$/u", 'msg'=>'请输入2-10位字母、汉字的姓名！'];
                return ['rule'=>"/^[\u4e00-\u9fa5_a-zA-Z]{2,10}$/", 'msg'=>'请输入2-10位字母、汉字的姓名！'];
                break;
            case 'name':
                return ['rule'=>"/^[\x{4e00}-\x{9fa5}_a-zA-Z]{2,10}$/u", 'msg'=>'请输入2-10位字母、汉字的姓名！'];
                break;
            default:
                throw new HttpException(404,'配置文件缺失!');
        }
    }
    /**
     * 验证数据
     * @param $data输入数据
     * @param $rule规则
     * @return bool
     */
    public static function data($data){
        if(isset($data) && is_array($data)){
            foreach($data as $k=>$v){
                $rule = self::get($k);
                if(!isset($v) || !preg_match($rule['rule'], $v)){
                    $result['status'] = 0;
                    $result['msg'] = $rule['msg'];
                    exit(json_encode($result));
                }
            }
        }
    }
}